package com.atjava.nebula.core.dao.dialect;

import java.math.BigDecimal;
import java.math.BigInteger;

public class SQLServerDialect implements Dialect {

	protected static final String SQL_END_DELIMITER = ";";	

	public String getLimitString(String sql, int offset, int limit,Object[] parameters) {
		sql = setParam(sql,parameters);
		//parameters=null;
		sql = trim(sql);
		//调用存储过程实现分页
		return new StringBuffer().append("exec Paging'").append(sql).append(
				"',").append(offset / limit + 1).append(",").append(limit).toString();
//		if ( offset > 0 ) {
//			throw new UnsupportedOperationException( "sql server has no offset" );
//		}
//		return new StringBuffer( sql.length() + 8 )
//				.append( sql )
//				.insert( getAfterSelectInsertPoint( sql ), " top " + limit )
//				.toString();
	}

//	static int getAfterSelectInsertPoint(String sql) {
//		int selectIndex = sql.toLowerCase().indexOf( "select" );
//		final int selectDistinctIndex = sql.toLowerCase().indexOf( "select distinct" );
//		return selectIndex + ( selectDistinctIndex == selectIndex ? 15 : 6 );
//	}
	
	public boolean supportsLimit() {
		return true;
	}

	/**把所有参数直接转移成最终的Sql语句
	 * @param sql
	 * @param parameters
	 * @return
	 */
	private String setParam(String sql , Object[]parameters){
		if(parameters.length>0){
			//如果将Integer类型默认加‘’时，分页报错，所以要首先替换
			sql=sql.replace("'", "''");
			String []sqlSect=sql.split("\\?");
			StringBuilder sqlStr=new StringBuilder();
			for(int i=0 ; i< parameters.length ; i++){
				sqlStr.append(sqlSect[i]);
				Object para=parameters[i];
				if(		   para instanceof Integer 
						|| para instanceof Double
						|| para instanceof BigDecimal
						|| para instanceof BigInteger
						|| para instanceof Float)
					sqlStr.append(para.toString());
				else if(para instanceof Boolean){
					if((Boolean)para)
						sqlStr.append("1");
					else
						sqlStr.append("0");
				}
				else //其它类型（包括日期型），都加上单引号
					sqlStr.append("''").append(para.toString()).append("''");
				parameters[i]=null;
					
			}
			sqlStr.append(sqlSect[sqlSect.length-1]);
			return sqlStr.toString();
		}
		else
		{
			sql=sql.replace("'", "''");
			return sql;
		}
	}
	
	private String trim(String sql) {
		sql = sql.trim();
		if (sql.endsWith(SQL_END_DELIMITER)) {
			sql = sql.substring(0, sql.length() - 1
					- SQL_END_DELIMITER.length());
		}
		return sql;
	}

}
